import axios from 'axios'
import Element from 'element-ui'
import router from './router'
import store from './store'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
const service = axios.create({
    baseURL: "http://localhost:8090/",
    // 超时
    timeout: 100000
})

service.interceptors.request.use(
config => {
    const token = localStorage.getItem("token")
        if (token) {
            config.headers['Authorization'] = 'Bearer ' + token
        }
       return config;
    },
error => {
        return Promise.reject(error);
    }
);

service.interceptors.response.use(
    response => {
        let res = response.data;
        if (res.code === 200) {
          return res
        } else {
          Element.Message.error('错了哦，这是一条错误消息', {duration: 1 * 1000})
          return Promise.reject(response.data.msg)
        }
  },
  error => {
        if(error.response.data) {
          error.message = error.response.data.msg?error.response.data.msg:error.response.data
        }
        if(error.response.status === 401) {
          store.commit("REMOVE_INFO")
          router.push("/login")
        }
        Element.Message.error(error.message, {duration: 1 * 1000})
        return Promise.resolve(error)
  }
)

export default service
